<template>
  <div>
    <div>
      <FormPanel
        ref="formPanel"
        :list="formList"
        :cols="1"
        :formType="type"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />
      <el-form
        :model="botform"
        :rules="rules"
        ref="addSearchForm"
        size="mini"
        label-width="80px"
        inline-message
      >
        <el-form-item :disabled="type === 'show'" v-if="botform.activityType == '10061002'" label="活动地址" prop="activityAddress">
          <el-input v-model="botform.activityAddress" style="width:300px" placeholder="地址" />
          <el-button v-if="type !== 'show'" type="text" @click="showbaiduMap">点击地图</el-button>
        </el-form-item>
        <!-- 图文 -->
        <el-form-item label="活动内容" prop="content">
          <div class="contents" v-if="type === 'show'" style="height:350px;border: 1px solid #ccc;overflow:auto;" v-html="botform.content"></div>
          <Tinymce v-else v-model="botform.content" :height="300" actionUrl="/api/file/oss/upload" />
        </el-form-item>
        <el-form-item v-if="type !== 'show'" label prop="disclaimer">
          <el-popover placement="top-start" title="免责声明" width="400" trigger="hover">
            <div style="border-top: 1px solid #eee;padding:'0';margin:'0';">
              <p>1. 本平台不对用户发布的任何内容(包括但不限于文章、图片、视频)的准确性进行保证。</p>
              <p>2. 用户需对所发表的内容负责，因所发表内容引发的一切纠纷，由该内容的发表者承担全部法律及连带责任。</p>
            </div>
            <el-radio v-model="radio" label="disclaimer" slot="reference">
              已阅读并同意
              <span style="color:#1588FF;">《免责声明》</span>
            </el-radio>
          </el-popover>
        </el-form-item>
      </el-form>
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="preview('addSearchForm')">预 览</el-button>
      <el-button @click="closeDialog">取 消</el-button>
      <!-- <el-button
        :disabled="isDisabled"
        @click="saveDialog('addSearchForm','save')"
        type="primary"
      >保 存</el-button>
      <el-button
        :disabled="isDisabled"
        @click="saveDialog('addSearchForm','release')"
        type="primary"
      >发 布</el-button> -->
        <multiuse-button :disabled="isDisabled" type="primary" :click="saveDialog.bind(this, 'addSearchForm','save')" :auth-list="auths" auth-mark="/api/information/activityInfo/saveFromPc">保 存</multiuse-button>
        <multiuse-button :disabled="isDisabled" type="primary" :click="saveDialog.bind(this, 'addSearchForm','release')" :auth-list="auths" auth-mark="/api/information/activityInfo/publish?id=${id}">发 布</multiuse-button>
    </div>
    <!--详情dialog-->
    <preview-dialog type="activity" ref="preview-dialog" />

    <el-dialog
      title="地图选择"
      :visible.sync="dialogVisible"
      width="50%"
      :append-to-body="true"
      :before-close="handleClose"
    >
      <div id="r-result" style="margin-bottom:10px;">
        城市名:
        <el-input
          id="cityName"
          v-model="searchCity"
          type="text"
          style="width:200px;margin-right:10px;"
        />
        <el-button type="primary" size="small" plain @click="theLocation()">切换城市</el-button>
      </div>
      <el-form
        :inline="true"
        ref="searchForm"
        :model="searchForm"
        :rules="searchrules"
        class="demo-form-inline"
      >
        <el-form-item label="城市名" prop="searchcity">
          <el-input v-model="searchForm.searchcity" placeholder="城市名"></el-input>
        </el-form-item>
        <el-form-item label="完整地址" prop="searchAddress">
          <el-input v-model="searchForm.searchAddress" placeholder="完整地址"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchLocation('searchForm')">搜索</el-button>
        </el-form-item>
      </el-form>
      <div v-if="mapInfo.address">
        <span>当前选中地址：{{ mapInfo.address }}</span>
        <div>
          <span>经度：{{ mapInfo.point.lng }}</span>
          <span>纬度：{{ mapInfo.point.lat }}</span>
        </div>
      </div>

      <div id="allmap" style="width:550px;height:300px;"></div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setmapInfo()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { saveActivity, delActivity, publishActivity, offActivity, stopSign, checkSign, activityDetail, getAllModal } from '@/api/community/activity/index';
import { dictionary } from '@/utils/dictMixin';
import { tcCodeList } from '@/api/community/news/index';
import previewDialog from '@/components/community/previewDialog';
import { parseTime } from '@/utils/index';
import MP from '@/assets/js/map';

import { authority } from '@/utils/authMixin';
export default {
  name: 'NewsModal',
  mixins: [dictionary,authority],
  components: {
    previewDialog
  },
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.saveData = null;
    return {
      formList: this.createFormList(),
      action: `/api/file/oss/upload/`,
      radio: '',
      botform: {
        activityType: '',
        activityAddress: '',
        content: '',
        isFullpush: ''
      },
      rules: {
        activityAddress: [{ required: true, message: '请填写活动地址', trigger: 'blur' }],
        content: [{ required: true, message: '请填写活动内容', trigger: 'blur' }]
      },
      isDisabled: false, //表单重复提交
      dialogVisible: false,
      searchCity: '', //查询城市
      map: undefined,
      mapInfo: {}, //定位详情
      searchForm: {
        searchcity: '',
        searchAddress: ''
      },
      searchrules: {
        searchcity: [{ required: true, message: '请填写搜索城市', trigger: 'blur' }],
        searchAddress: [{ required: true, message: '请填写完整地址', trigger: 'blur' }]
      }
    };
  },
  created() {
    this.init();
    this.getTccodeList('1006', 'activityType');
    this.getModalList();
  },
  methods: {
    handleChange(value) {
      console.log(value);
    },
    successHandler(val) {
      console.log('pic', val);
      this.botform.listPic = val;
    },
    init() {
      if (this.type === 'edit' || this.type === 'show') {
        // 更新接口需要的记录 ID
        this.recordId = this.rowData.id;
        let rowData = { ...this.rowData };
        if (typeof rowData.listPic !== 'object') {
          let arr = [];
          arr.push(rowData.listPic);
          rowData.listPic = arr;
        }
        rowData.activityTime = [parseTime(rowData.activityStartTime), parseTime(rowData.activityEndTime)];
        rowData.signTime = [parseTime(rowData.signStartTime), parseTime(rowData.signEndTime)];
        rowData.activityType = rowData.activityType.code;
        rowData.publishStatus = rowData.publishStatus.code;
        rowData.carName = rowData.brandId+',' +rowData.seriesId+',' +rowData.modelId+','  +rowData.packageId+',' +rowData.colorId;
        this.formList.forEach(x => {
          x.initialValue = rowData[x.fieldName];
        });
        this.botform = rowData
        this.isDisabled = false;
      }
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '标题',
          fieldName: 'activityTitle',
          rules: [{ required: true, message: '请输入活动名称', trigger: 'blur' }, { min: 2, max: 100, message: '长度在2到100个字符', trigger: 'blur' }]
        },
        {
          type: 'UPLOAD_IMG',
          label: '活动图片',
          fieldName: 'listPic',
          placeholder: '请选择图片',
          // style: { width: '250px' },
          initialValue: [],
          rules: [{ required: true, message: '请选择图片', trigger: 'change' }],
          upload: {
            actionUrl: '/api/file/oss/upload',
            fixedSize: [5, 2],
            isCalcHeight: true
          }
        },
        {
          type: 'RANGE_DATE',
          label: '活动时间',
          fieldName: 'activityTime',
          initialValue: [],
          isAfter: true,
          rules: [{ required: true, message: '请选择活动时间', trigger: 'blur' }],
        },
        {
          type: 'INPUT_CASCADER',
          label: '活动车型',
          fieldName: 'carName',
          placeholder: '请选择',
          options: { titles: ['品牌', '车系', '车型', '配置', '颜色'] },
          itemList: []
        },
        {
          type: 'RANGE_DATE',
          label: '报名时间',
          fieldName: 'signTime',
          initialValue: [],
          isAfter: true,
          rules: [{ required: true, message: '请选择报名时间', trigger: 'blur' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '可报名人数',
          fieldName: 'maxNum',
          initialValue: 0,
          style: { width: '250px' },
          annotation: '(未设置时报名人数无上限)',
          rules: []
        },
        {
          type: 'SELECT',
          label: '活动类型',
          fieldName: 'activityType',
          style: { width: '250px' },
          placeholder: '请选择',
          itemList: [],
          rules: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
          change: val => {
            this.activityTypeChange(val);
          }
        }
      ];
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    async getTccodeList(tcCode, name) {
      const res = await tcCodeList(tcCode);
      if (res.resultCode === 200) {
        this.formList.find(item=>item.fieldName===name).itemList = res.data.map(x => ({ value: x.codeId, text: x.codeCnDesc }));
      }
    },
    // 活动车型
    async getModalList() {
      const res = await getAllModal(1);
      // console.log('车型信息', res)
      if (res.resultCode === 200) {
        this.formList.find(item=>item.fieldName==='carName').itemList = res.data;
      }
    },
    saveDialog(formName, status) {
      this.$refs.formPanel.SUBMIT_FORM();
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.save(status);
        } else {
          this.$message.info('请填写必填项!');
          return false;
        }
      });
    },
    async save(status) {
      let saveData = { ...this.saveData };
      if (status === 'release') {
        saveData.publishStatus = 20221002; // 发布状态先设置为已发布
        saveData.activityStatus = 10081002; // 活动状态先设置为未开始
      } else {
        saveData.publishStatus = 20221001; // 发布状态先设置为未发布
        // this.saveData.activityStatus = 10081001;   // 活动状态先设置为未开始
      }
      this.isDisabled = true;
      let data = {
        radio: this.radio
      };
      // 校验是否选择免责声明
      if (status === 'release' && (data.radio == null || data.radio == '')) {
        this.$confirm('请同意免责声明!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        this.isDisabled = false;
        return false;
      }
      saveData.listPic = saveData.listPic[0];
      // 处理时间 activityStartTime
      if (saveData.activityTime != null && saveData.activityTime.length > 0) {
        saveData.activityStartTime = saveData.activityTime[0];
        saveData.activityEndTime = saveData.activityTime[1];
      }
      if (saveData.signTime != null && saveData.signTime.length > 0) {
        saveData.signStartTime = saveData.signTime[0];
        saveData.signEndTime = saveData.signTime[1];
      }

      var activity_date = new Date(saveData.activityEndTime);
      saveData.activityEndTime = activity_date.getTime();
      // log( '活动截止时间戳',this.saveData.activityEndTime)

      var sign_date = new Date(saveData.signEndTime);
      saveData.signEndTime = sign_date.getTime();
      // log( '报名截止时间戳',this.saveData.signEndTime)

      if (saveData.signEndTime > saveData.activityEndTime) {
        this.$message.info('报名结束时间不得晚于活动结束时间!');
        this.isDisabled = false;
        return false;
      } else {
        saveActivity({ ...this.botform, ...saveData })
          .then(res => {
            this.isDisabled = false;
            if (res.resultCode === 200) {
              this.closeDialog('refresh');
            }else{
              this.$message.info(res.errMsg);
            }
          })
          .catch(err => {
            this.$message.info(err.errMsg);
            this.isDisabled = false;
          });
        // let res = await saveActivity({...this.botform,...saveData});
        // if (res.resultCode === 200) {
        //   this.isDisabled = false
        //   this.closeDialog('refresh');
        // }else{
        //   this.isDisabled = false
        // }
      }
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    },
    // 预览
    preview(formName) {
      let token = localStorage.getItem('token'),
        appId = localStorage.getItem('appId');
      // this.$refs['preview-dialog'].open('https://cscyx.yycsy.com/im_h5/cyx/news/index.html?userToken=1&newsId=50&appId=a689d54406b9c6ee&imChannel=Client')
      this.$refs.formPanel.SUBMIT_FORM();
      this.$refs[formName].validate(valid => {
        if (valid) {
          let saveData = { ...this.saveData };
          // this.saveData.activityStatus = 10081001
          saveData.publishStatus = 20221000;
          saveData.listPic = saveData.listPic[0];
          // 处理时间 activityStartTime
          if (saveData.activityTime != null && saveData.activityTime.length > 0) {
            saveData.activityStartTime = saveData.activityTime[0];
            saveData.activityEndTime = saveData.activityTime[1];
          }
          if (saveData.signTime != null && saveData.signTime.length > 0) {
            saveData.signStartTime = saveData.signTime[0];
            saveData.signEndTime = saveData.signTime[1];
          }
          // 保存活动
          saveActivity({ ...this.botform, ...saveData })
            .then(res => {
              // this.$message.success("保存成功!");
              if (res.data) {
                this.rowData.id = res.data;
              }
              let url = `${window.location.origin}/im_h5/cyx/active/index.html?userToken=${token}&previewId=${res.data.id}&appId=${appId}&imChannel=Client`;
              // let url = `http://cscyx.yycsy.com/im_h5/cyx/active/index.html?userToken=${token}&previewId=${res.data.id}&appId=${appId}&imChannel=Client`
              this.$refs['preview-dialog'].open(url);
              // this.$emit('getList')
              // this.$refs.dialog.close()
            })
            .catch(err => {
              this.$message.info('res.errMsg');
              return false;
            });
        } else {
          this.$message.info('请填写必填项!');
          return false;
        }
      });
    },
    // 活动类型
    activityTypeChange(value) {
      this.botform.activityType = value;
      if (value == '10061002') {
        // this.botform.addressStatus = "show";
      } else {
        // this.botform.addressStatus = "hidden";
        this.botform.activityAddress = null;
        this.botform.point = {};
        // this.$refs['form'].clearValidate('activityAddress')
      }
    },
    showbaiduMap() {
      let self = this;
      this.dialogVisible = true;
      setTimeout(function() {
        self.baiduMap();
      }, 500);
    },
    // 地图
    baiduMap() {
      // var map = new BMap.Map('allmap')
      // var point = new BMap.Point(111.742579, 40.818675)
      // map.centerAndZoom(point, 12)
      // var marker = new BMap.Marker(point)  // 创建标注
      // map.addOverlay(marker)              // 将标注添加到地图中
      let self = this;
      MP().then(BMap => {
        // 百度地图API功能
        self.map = new BMap.Map('allmap');
        var point = new BMap.Point(116.331398, 39.897445);
        self.map.centerAndZoom(point, 12);

        self.map.enableScrollWheelZoom(); //启用滚轮放大缩小，默认禁用
        self.map.enableContinuousZoom(); //启用地图惯性拖拽，默认禁用
        //添加缩放平移控件
        self.map.addControl(new BMap.NavigationControl());
        //添加比例尺控件
        self.map.addControl(new BMap.ScaleControl());
        //添加缩略图控件
        self.map.addControl(new BMap.OverviewMapControl());
        //添加地图类型控件
        self.map.addControl(new BMap.MapTypeControl());

        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(
          function(r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
              // var mk = new BMap.Marker(r.point);
              // self.map.addOverlay(mk);
              self.map.panTo(r.point);
              // console.log(r)
              // alert('您的位置：'+r.point.lng+','+r.point.lat);
            } else {
              alert('failed' + this.getStatus());
            }
          },
          { enableHighAccuracy: true }
        );

        // 逆地址解析
        var geoc = new BMap.Geocoder();
        self.map.addEventListener('click', function(e) {
          var pt = e.point;
          geoc.getLocation(pt, function(rs) {
            // console.log(rs)
            self.mapInfo = rs;

            // var addComp = rs.addressComponents;
            // alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
          });
        });
      });
    },
    // 设置地址 确定
    setmapInfo() {
      this.botform.activityAddress = this.mapInfo.address;
      this.botform.point = this.mapInfo.point;
      this.handleClose();
      this.searchcity = '';
      this.searchForm = {};
    },
    handleClose() {
      // console.log('handleClose')
      this.dialogVisible = false;
      this.map = undefined;
      this.mapInfo = {};
      this.searchcity = '';
      this.searchForm = {};
    },
    // 根据地址获取位置
    searchLocation(formName) {
      let self = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          MP().then(BMap => {
            // 创建地址解析器实例
            var myGeo = new BMap.Geocoder();
            // 将地址解析结果显示在地图上,并调整地图视野
            myGeo.getPoint(
              self.searchForm.searchAddress,
              function(point) {
                if (point) {
                  let newobj = {};
                  self.map.centerAndZoom(point, 16);
                  self.map.addOverlay(new BMap.Marker(point));
                  newobj.address = self.searchForm.searchAddress;
                  newobj.point = point;
                  self.mapInfo = newobj;
                } else {
                  self.$message.error('您选择地址没有解析到结果!');
                }
              },
              self.searchForm.searchcity
            );
          });
        }
      });
    },
    theLocation() {
      this.map.centerAndZoom(this.searchCity, 11); // 用城市名设置地图中心点
    }
  }
};
</script>

<style lang="less" scoped>
</style>
